package com.zhengqing.common.netty.server.tcp.endecoder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhengqing.common.netty.model.NettyMsgBase;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.StandardCharsets;

/**
 * <p> 消息编码器 </p>
 *
 * @author zhengqingya
 * @description
 * @date 2024/2/26 11:11
 */
public class TcpMsgEncoder extends MessageToByteEncoder<NettyMsgBase> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, NettyMsgBase sendInfo, ByteBuf byteBuf) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        String content = objectMapper.writeValueAsString(sendInfo);
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        // 写入长度
        byteBuf.writeLong(bytes.length);
        // 写入命令体
        byteBuf.writeBytes(bytes);
    }

}
